package com.alpsot.spotcheck.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.alpsoft.spotcheck.adapter.BackColorListViewAdapter;
import com.alpsoft.spotcheck.db.DBManager;
import com.alpsoft.spotcheck.db.SQLiteTemplate;
import com.alpsoft.spotcheck.db.SQLiteTemplate.RowMapper;
import com.alpsoft.spotcheck.impl.HandleMsg;
import com.alpsoft.spotcheck.model.EqResult;
import com.alpsoft.spotcheck.model.Equipment;
import com.alpsoft.spotcheck.status.EquipmentType;
import com.alpsoft.spotcheck.util.DataHelper;
import com.alpsoft.spotcheck.util.GlobalVar;
import com.alpsoft.spotcheck.util.SharedPreferencesUtils;
import com.alpsoft.spotcheck.util.UploadDataManager;
import com.alpsoft.spotcheck.util.Utils;
import com.alpsot.lkspotcheck.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.pda.scan.CardThread;
import cn.pda.scan.ScanThread;

/**
 * 日点检
 *
 * @author Nasir
 */
public class DailyCheck extends Fragment implements HandleMsg, OnClickListener {

    private ListView listview;
    private DBManager dbManager;
    private SQLiteDatabase db;
    private SimpleAdapter adapter;
    private List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
    private final int REQUEST = 1;
    private final int RESULT = 2;
    private DataHelper dh;
    private Context context;
    private SQLiteTemplate st;
    private Intent intent;
    private String[] pcode = new String[6];
    private int curs = 0;
    private View view;

    private Button tab_back;
    private Button upload;

    // 震动对象
    public long[] pattern = {100, 400, 100, 400}; // 停止 开启 停止 开启

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflateAndSetupView(inflater, container, savedInstanceState,
                R.layout.activity_tab_eq_listview);
        tab_back = (Button) view.findViewById(R.id.tab_back);
        upload = (Button) view.findViewById(R.id.upload);
        tab_back.setOnClickListener(this);
        upload.setOnClickListener(this);
        return view;
    }

    private View inflateAndSetupView(LayoutInflater inflater,
                                     ViewGroup container, Bundle savedInstanceState, int layoutResourceId) {
        View layout = inflater.inflate(layoutResourceId, container, false);
        return layout;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this.getActivity();
        intent = this.getActivity().getIntent();
        curs = 0;
        pcode[curs] = null;
        dh = new DataHelper(context);
        dbManager = DBManager.getInstance(context, GlobalVar.databaseName);
        st = SQLiteTemplate.getInstance(dbManager, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        dataList = getData(null);
        adapter = new BackColorListViewAdapter(context, dataList,
                R.layout.activity_tab_eq, new String[]{"name", "number"},
                new int[]{R.id.text1, R.id.text2});
        listview = (ListView) view.findViewById(R.id.listview);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                HashMap<String, Object> map = (HashMap<String, Object>) listview
                        .getItemAtPosition(position);
                String node_type = (String) map.get("node_type");
                String parentCode = (String) map.get("parentCode");
                String self_code = (String) map.get("self_code");
                // if("BJ".equalsIgnoreCase(node_type)){
                if (EquipmentType.Unit.equalsIgnoreCase(node_type)) {
                    // EquipmentType.java
                    String cycle_type = (String) map.get("cycle_type");
                    String belongEq = (String) map.get("belongEq");
                    Intent intent = new Intent();
                    intent.putExtra("cycle_type", cycle_type);
                    intent.putExtra("belongEq", belongEq);
                    intent.putExtra("tab_code", parentCode);
                    // 判断code和time
                    if (null != GlobalVar.scanCode
                            && "".equals(GlobalVar.scanCode)
                            && isEffective(self_code)) {
                        intent.putExtra("isCheckMan", "true");
                    } else {
                        intent.putExtra("isCheckMan", "false");
                    }
                    intent.setClass(context, CheckItemActivity.class);
                    DailyCheck.this.getActivity().startActivityForResult(intent, REQUEST);
                } else {

                    if (curs > 5) {
                        curs = 5;
                    }
                    pcode[curs] = parentCode != null && !parentCode.equals("") ? parentCode
                            : null;
                    curs++;

                    dataList = getData(self_code);
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab_back:
                curs--;
                if (curs < 0) {
                    curs = 0;
                }
                dataList = getData(pcode[curs]);
                adapter.notifyDataSetChanged();
                break;
            case R.id.upload:
                new AlertDialog.Builder(context)
                        .setTitle("保存过的上传后不能再修改，请确认要上传吗？")
                        .setIcon(android.R.drawable.ic_dialog_info)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        if (dh.hasLocalData()) {
                                            if (LoginActivity.zhLogin) {
                                                Utils.loginByName(
                                                        context,
                                                        DailyCheck.this,
                                                        SharedPreferencesUtils
                                                                .getLoginInfo(
                                                                        context)
                                                                .getUserName(),
                                                        SharedPreferencesUtils
                                                                .getLoginInfo(
                                                                        context)
                                                                .getPassword(),
                                                        "DailyCheck");
                                                GlobalVar.ts.speak("开始上传数据");
                                            } else {
                                                Utils.login(
                                                        context,
                                                        DailyCheck.this,
                                                        SharedPreferencesUtils
                                                                .getLoginInfo(
                                                                        context)
                                                                .getIcCode(),
                                                        "DailyCheck");
                                                GlobalVar.ts.speak("开始上传数据");
                                            }
                                        } else {
                                            Intent intent = new Intent();
                                            intent.setClass(context,
                                                    LoginActivity.class);
                                            context.startActivity(intent);
                                            DailyCheck.this.getActivity().finish();
                                        }
                                    }
                                })
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                    }
                                }).show();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST && resultCode == RESULT) {
            String code = data.getStringExtra("tabCode");
            dataList = getData(code);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public Handler getHandler() {
        // TODO Auto-generated method stub
        return null;
    }

    public Handler myHandler = new Handler() {
        @SuppressLint("ShowToast")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GlobalVar.msg_LoginSuccess:
                    if (dh.hasLocalData()) {
                        UploadDataManager ud = new UploadDataManager(context);
                        ud.checkDataUpInfo("update_dj");
                    } else {
                        msg.obj = "无日点检数据";
                        Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    }
                    break;
                case GlobalVar.msg_LoginFailure:
                    Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case GlobalVar.msg_UploadSuccess:
                    // 跳转至登录页面
                    Intent intent = new Intent();
                    intent.setClass(context, LoginActivity.class);
                    context.startActivity(intent);
                    DailyCheck.this.getActivity().finish();
                    // LoginActivity2.instance.finish();
                    break;
                case ScanThread.SCAN:
                    GlobalVar.scanCode = msg.getData().getString("data").trim();
                    GlobalVar.scanTime = System.currentTimeMillis();
                    getScanEquip();
                    break;
                case CardThread.READ:
                    String data = msg.getData().getString("data");
                    if (null != data) {
                        GlobalVar.scanCode = data.substring(0, 12);
                    }
                    GlobalVar.scanTime = System.currentTimeMillis();
                    msg.obj = getScanEquip();
                    if (msg.obj != null) {
                        Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    public String getScanEquip() {
        String temp = null;
        Equipment eqObj = st.queryForObject(new RowMapper<Equipment>() {
                                                @Override
                                                public Equipment mapRow(Cursor cursor, int index) {
                                                    Equipment eq = new Equipment();
                                                    eq.setEquipmentId(cursor.getString(cursor
                                                            .getColumnIndex("EQUIPMENT_ID")));
                                                    eq.setEquipmentType(cursor.getString(cursor
                                                            .getColumnIndex("EQUIPMENT_TYPE")));
                                                    eq.setEquipmentName(cursor.getString(cursor
                                                            .getColumnIndex("EQUIPMENT_NAME")));
                                                    return eq;
                                                }
                                            }, "select * from EQ_EQUIPMENT where SCAN_CODE=?",
                new String[]{GlobalVar.scanCode});
        if (eqObj != null) {
            if (EquipmentType.Unit.equalsIgnoreCase(eqObj.getEquipmentType())) {
                Intent intent1 = new Intent();
                String parentCode1 = eqObj.getParentCode();
                String cycle_type1 = "day";
                String belongEq1 = eqObj.getEquipmentId();
                intent1.putExtra("cycle_type", cycle_type1);
                intent1.putExtra("belongEq", belongEq1);
                intent1.putExtra("tab_code", parentCode1);
                intent1.putExtra("isCheckMan", "true");
                intent1.setClass(context, CheckItemActivity.class);
                DailyCheck.this.getActivity().startActivityForResult(intent1, REQUEST);
            } else {
                dataList = getData(eqObj.getEquipmentId());
                adapter.notifyDataSetChanged();
                if (null == dataList || dataList.isEmpty()) {
                    temp = "无日点检";
                    GlobalVar.ts.speak("无日点检");
                } else {
                    temp = "设备、" + eqObj.getEquipmentName();
                    GlobalVar.ts.speak("设备、" + eqObj.getEquipmentName());
                }
            }
        } else {
            temp = "查无此设备";
            GlobalVar.ts.speak("查无此设备");
        }
        GlobalVar.scanCode = null;
        return temp;
    }

    private List<Map<String, Object>> getData(String parentCode) {
        // 查询设备
        String sql = genSql(parentCode);
        SQLiteTemplate st = SQLiteTemplate.getInstance(dbManager, false);
        List<EqResult> EqResultList = st.queryForList(
                new RowMapper<EqResult>() {
                    @Override
                    public EqResult mapRow(Cursor cursor, int index) {
                        EqResult eq = new EqResult();
                        eq.setEquipmentName(cursor.getString(cursor
                                .getColumnIndex("EQUIPMENT_NAME")));
                        eq.setConNo(cursor.getString(cursor
                                .getColumnIndex("conNo")));
                        eq.setEquipmentid(cursor.getString(cursor
                                .getColumnIndex("equipmentid")));
                        eq.setCycle_type(cursor.getString(cursor
                                .getColumnIndex("CYCLE_TYPE")));
                        eq.setNode_type(cursor.getString(cursor
                                .getColumnIndex("EQUIPMENT_TYPE")));
                        eq.setSelf_code(cursor.getString(cursor
                                .getColumnIndex("SELF_CODE")));
                        eq.setFinishNo(cursor.getString(cursor
                                .getColumnIndex("finishNo")));
                        eq.setParentCode(cursor.getString(cursor
                                .getColumnIndex("PARENT_CODE")));
                        return eq;
                    }

                }, sql.toString(), null);

        dataList.clear();

        for (EqResult eq : EqResultList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", eq.getEquipmentName());
            map.put("number", eq.getConNo());
            map.put("belongEq", eq.getEquipmentid());
            map.put("cycle_type", eq.getCycle_type());
            map.put("node_type", eq.getNode_type());
            map.put("self_code", eq.getSelf_code());
            map.put("parentCode", eq.getParentCode());
            String conStr = eq.getConNo();
            String finishStr = eq.getFinishNo();
            int conNo = 0;
            int finishNo = 0;
            if (conStr != null)
                conNo = Integer.parseInt(conStr);
            if (finishStr != null)
                finishNo = Integer.parseInt(finishStr);
            if (finishNo > 0 && finishNo < conNo)
                map.put("color", "yellow");
            else if (finishNo > 0 && finishNo == conNo)
                map.put("color", "green");
            else
                map.put("color", "transparent");
            dataList.add(map);
        }
        return dataList;
    }

    private String genSql(String parentCode) {

        String con = "";
        if (null == parentCode) {
            con = "(SELECT * FROM EQ_EQUIPMENT EQ WHERE EQ.DEPT_ID is not null)";
        } else {
            con = "(SELECT * FROM EQ_EQUIPMENT EQ WHERE EQ.PARENT_CODE = '"
                    + parentCode + "')";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("SELECT * ");
        sb.append(" FROM ");
        sb.append("( ");
        sb.append("	SELECT COUNT(*) conNo, T.EQUIPMENT_ID equipmentid,A.CYCLE_TYPE FROM ");
        sb.append(con + " T,");
        sb.append("(select * from EQ_EQUIPMENT s, eq_check_item c where s.equipment_id = c.equipment_id and c.CYCLE_TYPE='day') A ");
        sb.append(" WHERE A.SELF_CODE LIKE T.SELF_CODE || '%' ");
        sb.append("GROUP BY T.EQUIPMENT_ID");
        sb.append(") M ");
        sb.append("LEFT JOIN ");

        sb.append("(SELECT COUNT(*) finishNo,AA.EQUIPMENT_ID from " + con
                + " AA,(select * from EQ_EQUIPMENT ss, eq_check_item cc,");
        sb.append("eq_check_record rr where ss.equipment_id = cc.equipment_id and cc.CHECK_ITEM_ID = rr.CHECK_ITEM_STRATEGY_ID ");
        sb.append("and cc.CYCLE_TYPE = 'day' and ((datetime(rr.START_TIME)<datetime('now','localtime') and datetime(rr.END_TIME)>datetime('now','localtime') and ");
        sb.append("cc.CYCLE_UNIT != 'day') or cc.CYCLE_UNIT = 'day') and rr.check_user_id is not null) BB ");
        sb.append("where BB.SELF_CODE LIKE AA.SELF_CODE || '%' group by AA.EQUIPMENT_ID)  VV  ON vv.EQUIPMENT_ID=M.equipmentid ");

        sb.append(",EQ_EQUIPMENT Z ");
        sb.append("WHERE M.equipmentid = Z.EQUIPMENT_ID");
        return sb.toString();
    }

    private boolean isEffective(String self_code) {
        Equipment obj = st.queryForObject(new RowMapper<Equipment>() {
                                              @Override
                                              public Equipment mapRow(Cursor cursor, int index) {
                                                  Equipment eq = new Equipment();
                                                  eq.setEquipmentType(cursor.getString(cursor
                                                          .getColumnIndex("EQUIPMENT_TYPE")));
                                                  eq.setParentCode(cursor.getString(cursor
                                                          .getColumnIndex("PARENT_CODE")));
                                                  eq.setEquipmentId(cursor.getString(cursor
                                                          .getColumnIndex("EQUIPMENT_ID")));
                                                  eq.setSelfCode(cursor.getString(cursor
                                                          .getColumnIndex("SELF_CODE")));
                                                  return eq;
                                              }
                                          }, "select * from EQ_EQUIPMENT where SCAN_CODE=?",
                new String[]{GlobalVar.scanCode});
        String eqCode = obj.getSelfCode();

        boolean isParent = isParent(self_code, eqCode);
        Long result = GlobalVar.scanTime - System.currentTimeMillis();
        if (isParent && result <= 5 * 60 * 1000) {
            return true;
        }
        return false;
    }

    private boolean isParent(String code, String rootCode) {
        if (code.equals(rootCode)) {
            return true;
        }
        Equipment obj = st.queryForObject(
                new RowMapper<Equipment>() {
                    @Override
                    public Equipment mapRow(Cursor cursor, int index) {
                        Equipment eq = new Equipment();
                        eq.setParentCode(cursor.getString(cursor
                                .getColumnIndex("PARENT_CODE")));
                        eq.setDeptId(cursor.getString(cursor
                                .getColumnIndex("DEPT_ID")));
                        return eq;
                    }
                }, "select * from EQ_EQUIPMENT where SELF_CODE=?",
                new String[]{code});
        String pCode = obj.getParentCode();
        if (obj.getDeptId() == null) {
            if (pCode.equals(rootCode)) {
                return true;
            } else {
                isParent(pCode, rootCode);
            }
        }
        return false;
    }
}
